"""
Image processing for PowerPoint presentations.
"""

import os
from pathlib import Path
from typing import Tuple, Optional

from PIL import Image
from pptx.slide import Slide
from pptx.util import Inches

from ..styling.theme_manager import ThemeManager


class ImageProcessor:
    """Handles image processing and insertion into slides."""
    
    def __init__(self, theme_manager: ThemeManager):
        self.theme_manager = theme_manager
    
    def add_image_to_slide(self, slide: Slide, image_path: str, y_position: float) -> float:
        """
        Add an image to a slide at the specified Y position.
        Returns the height of the added image.
        """
        # Resolve image path
        resolved_path = self._resolve_image_path(image_path)
        if not resolved_path or not resolved_path.exists():
            raise FileNotFoundError(f"Image not found: {image_path}")
        
        # Get image constraints
        constraints = self.theme_manager.get_image_constraints()
        layout = self.theme_manager.get_layout_dimensions()
        
        # Calculate image dimensions
        image_width, image_height = self._calculate_image_size(
            resolved_path, 
            constraints['max_width'], 
            constraints['max_height']
        )
        
        # Center the image horizontally
        x_position = layout['content_left'] + (layout['content_width'] - image_width) / 2
        
        # Add image to slide
        slide.shapes.add_picture(
            str(resolved_path),
            x_position,
            y_position,
            image_width,
            image_height
        )
        
        return image_height
    
    def _resolve_image_path(self, image_path: str) -> Optional[Path]:
        """Resolve image path, handling relative paths."""
        path = Path(image_path)
        
        # If absolute path exists, use it
        if path.is_absolute() and path.exists():
            return path
        
        # Try relative to current working directory
        cwd_path = Path.cwd() / path
        if cwd_path.exists():
            return cwd_path
        
        # Try relative to common image directories
        common_dirs = ['images', 'img', 'assets', 'media']
        for dir_name in common_dirs:
            dir_path = Path.cwd() / dir_name / path.name
            if dir_path.exists():
                return dir_path
        
        return None
    
    def _calculate_image_size(self, image_path: Path, max_width: float, 
                            max_height: float) -> Tuple[float, float]:
        """Calculate the appropriate size for an image within constraints."""
        try:
            # Open image to get dimensions
            with Image.open(image_path) as img:
                original_width, original_height = img.size
            
            # Convert pixels to inches (assuming 96 DPI)
            dpi = 96
            original_width_inches = Inches(original_width / dpi)
            original_height_inches = Inches(original_height / dpi)
            
            # Calculate scaling factor to fit within constraints
            width_scale = max_width / original_width_inches
            height_scale = max_height / original_height_inches
            scale_factor = min(width_scale, height_scale, 1.0)  # Don't upscale
            
            # Calculate final dimensions
            final_width = original_width_inches * scale_factor
            final_height = original_height_inches * scale_factor
            
            return final_width, final_height
            
        except Exception as e:
            # If we can't determine size, use default constraints
            return max_width * 0.5, max_height * 0.5
    
    def validate_image(self, image_path: str) -> bool:
        """Validate that an image file exists and is readable."""
        try:
            resolved_path = self._resolve_image_path(image_path)
            if not resolved_path:
                return False
            
            # Try to open the image
            with Image.open(resolved_path) as img:
                img.verify()
            
            return True
        except Exception:
            return False
    
    def get_supported_formats(self) -> list:
        """Get list of supported image formats."""
        return ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp']
    
    def is_supported_format(self, image_path: str) -> bool:
        """Check if image format is supported."""
        path = Path(image_path)
        return path.suffix.lower() in self.get_supported_formats()